package com.goldgov.autotest.web;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.HttpHostConnectException;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.goldgov.autotest.json.SwaggerJson;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.Version;

@RestController
@RequestMapping("/autotest")
public class AutoTestController {

	@Value("${source-code.template-path}")
	private String templatePath;
	
	@GetMapping("/resource")
	public String resourceAnalysis(@RequestParam("hostUrl") String hostUrl) {
		hostUrl = hostUrl.endsWith("/") ? hostUrl : hostUrl + "/";
		CloseableHttpClient httpClient = HttpClients.createDefault();
		HttpGet httpMethod = new HttpGet(hostUrl + "swagger-resources");
		
		CloseableHttpResponse httpResponse = null;
        try {
        	httpResponse = httpClient.execute(httpMethod);
            return EntityUtils.toString(httpResponse.getEntity());
        } catch (Exception e) {
        	if(e instanceof HttpHostConnectException) {
        		throw new RuntimeException("远程服务器连接失败",e);
        	}
			throw new RuntimeException("请求swagger请求时发生异常",e);
		} finally {
			if(httpResponse != null) {
				try {
					httpResponse.close();
				} catch (IOException e) {}
			}
        }
	}
	
	@GetMapping("/api")
	public void apiAnalysis(@RequestParam("hostUrl") String hostUrl,@RequestParam("swaggerApi") String swaggerApi,HttpServletResponse response) {
		hostUrl = hostUrl.endsWith("/") ? hostUrl.substring(0,hostUrl.length() - 1) : hostUrl;
		
		CloseableHttpClient httpClient = HttpClients.createDefault();
		HttpGet httpMethod = new HttpGet(hostUrl + swaggerApi);
		
		CloseableHttpResponse httpResponse = null;
		String apiJson = null;
        try {
        	httpResponse = httpClient.execute(httpMethod);
        	apiJson = EntityUtils.toString(httpResponse.getEntity());
        } catch (Exception e) {
			throw new RuntimeException("请求swagger请求时发生异常",e);
		} finally {
			if(httpResponse != null) {
				try {
					httpResponse.close();
				} catch (IOException e) {}
			}
        }
        
		response.setHeader("Content-Disposition", "attachment; filename=\"funtion.txt\"");
		response.setCharacterEncoding("UTF-8");
		
        Configuration config = new Configuration(new Version(2, 3, 28));
		try {
			config.setDirectoryForTemplateLoading(new File(templatePath + File.separator + "autotest" + File.separator + "byurl"));
			Template template = config.getTemplate("funtion.txt","UTF-8");
			ObjectMapper om = new ObjectMapper();
			om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
			SwaggerJson readValue = om.readValue(apiJson,SwaggerJson.class);
			Map<String,Object> valueMap = new HashMap<>();
			valueMap.put("json", readValue);
			template.process(valueMap, response.getWriter());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
